package demo.practice.leetcode_eveyday;

public class P566 {


    public int[][] matrixReshape(int[][] nums, int r, int c) {
        if (nums == null || nums.length == 0 || nums[0].length == 0)
            return nums;//这是后可以算成无法转换

        int heightOld = nums.length;
        int widthOld = nums[0].length;

        if (heightOld * widthOld != r * c)
            return nums;//无法转换

        //元素的索引 为0 ~ heightOld*widthOld-1       平铺数组假想为 flat[heightOld*widthOld]
        //放入新矩阵里 为0 ~ r*c-1

        //nums[x][y]  平铺后的索引为  widthOld*x+y
        //平铺后flat[widthOld*x+y] 在 新数组中为  (widthOld*x+y)/c,(widthOld*x+y)%c
        int[][] target = new int[r][c];
        for (int i = 0; i < nums.length; i++) {
            for (int j = 0; j < nums[i].length; j++) {
                target[(widthOld*i+j)/c ][(widthOld*i+j)%c]=nums[i][j];
            }
        }

        return target;
    }

}
